package qiniu

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"github.com/qiniu/go-sdk/v7/auth"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"strconv"
	"zswei.xyz/manager/config"
	"zswei.xyz/manager/global"
)

// 获取上传的token
func getToken(q config.QiNiu) string {
	accessKey := q.AccessKey
	secretKey := q.SecretKey
	bucket := q.Bucket
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	mac := qbox.NewMac(accessKey, secretKey)
	upToken := putPolicy.UploadToken(mac)
	return upToken
}

// 获取上传的配置
func getCfg(q config.QiNiu) storage.Config {
	cfg := storage.Config{}
	// 空间对应的机房
	zone, _ := storage.GetRegionByID(storage.RegionID(q.Zone))
	cfg.Zone = &zone
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	return cfg

}

// UploadImage 上传图片  文件数组，前缀
func UploadImage(data []byte, imageName string, prefix string) (filePath string, err error) {
	if global.Config.Upload.UploadAdd != 1 {
		return "", errors.New("请启用七牛云上传")
	}
	q := global.Config.QiNiu
	l := global.Config.Upload
	if q.AccessKey == "" || q.SecretKey == "" {
		return "", errors.New("请配置accessKey及secretKey")
	}
	if float64(len(data))/1024/1024 > l.Size {
		return "", errors.New("文件超过设定大小")
	}
	upToken := getToken(q)
	cfg := getCfg(q)

	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	putExtra := storage.PutExtra{
		Params: map[string]string{},
	}
	dataLen := int64(len(data))

	// 获取当前时间
	key := fmt.Sprintf("%s/%s", prefix, imageName)

	err = formUploader.Put(context.Background(), &ret, upToken, key, bytes.NewReader(data), dataLen, &putExtra)
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%s", ret.Key), nil
}

// 获取删除文件鉴权
func delToken(q config.QiNiu) *auth.Credentials {
	accessKey := q.AccessKey
	secretKey := q.SecretKey
	mac := qbox.NewMac(accessKey, secretKey)
	return mac
}

func DelQiNiuImg(bucket string, keys []string) string {
	q := global.Config.QiNiu
	upToken := delToken(q)
	cfg := getCfg(q)
	formUploader := storage.NewBucketManager(upToken, &cfg) // 鉴权

	deleteOps := make([]string, 0, len(keys))
	for _, key := range keys {
		deleteOps = append(deleteOps, storage.URIDelete(bucket, key))
	}
	rets, _ := formUploader.Batch(deleteOps) // 执行批量操作
	if len(rets) == 0 {
		return "七牛云删除文件失败,未选择删除文件"
	}

	// 判断成功了几个或失败了几个
	var okCount []string  // 成功条数
	var errCount []string // 失败条数
	for _, ret := range rets {
		// 200 为成功
		if ret.Code == 200 {
			okCount = append(okCount, strconv.Itoa(ret.Code))
		} else {
			errCount = append(errCount, ret.Data.Error)
		}
	}

	return fmt.Sprintf("七牛云成功 %d 个-失败 %d 个", len(okCount), len(errCount))
}
